import 'package:flutter/material.dart';
import 'package:hygf/http/file_transfer/down_cap.dart';
import 'package:hygf/util/string_extension.dart';

import '../config/ApiConfig.dart';
import '../config/GlobalConfig.dart';
import '../config/RouteConfig.dart';
import '../http/DioClient.dart';
import '../http/file_transfer/VersionStatus.dart';
import '../res/HDColors.dart';
import '../res/my_colors.dart';
import '../util/HDNavigator.dart';
import '../util/LoadingUtils.dart';
import '../view/dialog/dialog_manager.dart';

class MinePage extends StatefulWidget {
  const MinePage({Key? key}) : super(key: key);

  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  List<MineListData> mineData = [];

  @override
  void initState() {
    super.initState();
    initData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      decoration: BoxDecoration(color: HDColors.white),
      child: ListView.separated(
        // 把listview顶上到状态栏的padding去掉 要不然没有appbar的时候会显示一个白色的状态栏
        padding: const EdgeInsets.only(top: 0),
        itemCount: mineData.length + 1,
        itemBuilder: (BuildContext context, int index) {
          if (index == 0) {
            return _getHeader();
          }
          if (index == mineData.length + 1) {
            return _getBottom();
          }
          return Container(
            color: Colors.white,
            child: ListTile(
                title: Text(mineData[index - 1].title),
                leading: getIcon(index - 1),
                trailing: mineData[index - 1].dot
                    ? Row(
                        mainAxisSize: MainAxisSize.min,
                        children: const [
                          CircleAvatar(
                            backgroundColor: Colors.red,
                            radius: 3,
                          ),
                          Icon(Icons.keyboard_arrow_right_rounded),
                        ],
                      )
                    : const Icon(Icons.keyboard_arrow_right_rounded),
                onTap: () => clickItem(index)),
          );
        },
        separatorBuilder: (BuildContext context, int index) {
          if (index == 0 || mineData[index - 1].isEnd) {
            return const Divider(
              height: 10,
              thickness: 10,
              color: MyColors.divider,
            );
          }
          return Container(
            padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
            child: const Divider(
              height: 1,
              color: MyColors.dividerColor,
            ),
          );
        },
      ),
    ));
  }

  clickItem(int index) async {
    switch (index) {
      case 1: // 用户协议
        HDNavigator.openToName(RouteConfig.webView,
            arguments: {"title": "用户协议", "url": "https://www.xieyimao.com/doc/detailzh/token/1735051738_6983"});
        break;
      case 2: // 隐私协议
        HDNavigator.openToName(RouteConfig.webView, arguments: {
          "title": "隐私协议",
          "url": "https://www.xieyimao.com/doc/detailzh/token/1735051512_4943"
        });
        break;
      case 3:
        var status = await DioClient().checkVersion(context, false);
        if (status == VersionStatus.current) {
          LoadingUtils.showInfo("已经是最新版本");
        }
        break;
    }

  }

  Widget getHeader() {
    return Container(
      decoration: BoxDecoration(
          gradient: LinearGradient(
              colors: [MyColors.primary, Colors.white],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              stops: [0.0, 1])),
      child: Container(
        height: 180,
        margin: EdgeInsets.fromLTRB(
            16, 16 + MediaQuery.of(context).padding.top, 16, 16),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(16)),
            color: Colors.white),
        child: Stack(
          children: [
            Container(
              padding: EdgeInsets.fromLTRB(16, 0, 0, 0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    GlobalConfig.loginEntity?.userName ?? "--",
                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Text(
                    GlobalConfig.loginEntity?.organizationName ?? "",
                    style: TextStyle(fontSize: 17),
                  )
                ],
              ),
            ),
            Positioned(
              child: Stack(
                alignment: Alignment.center,
                children: [
                  CircleAvatar(backgroundColor: Colors.blueAccent, radius: 40),
                  Text(
                    ApiConfig.userName.lastChars(1),
                    style: TextStyle(fontSize: 24, color: Colors.white),
                  ),
                ],
              ),
              right: 16,
              top: 45,
            )
          ],
        ),
      ),
    );
  }

  _getHeader() {
    return Container(
      child: Stack(
        children: [
          Container(
            height: 230,
            width: double.infinity,
          ),
          Positioned(
            left: 16,
            bottom: 33.05,
            child: Container(
              width: 60,
              height: 60,
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.white, width: 2),
                  borderRadius: BorderRadius.circular(30)),
              child: Center(
                child: CircleAvatar(
                  backgroundColor: Colors.blueAccent,
                  radius: 28,
                  child: Text(
                    ApiConfig.userName.lastChars(2),
                    style: TextStyle(fontSize: 16, color: Colors.white),
                  ),
                ),
              ),
            ),
          ),
          Positioned(
            left: 86,
            bottom: 71.05,
            child: Text(
              ApiConfig.userName,
              style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                  color: HDColors.black),
            ),
          ),
          Positioned(
            left: 86,
            bottom: 39.05,
            child: Container(
              decoration: BoxDecoration(
                color: "#216FF6".toColor()!.withOpacity(0.15),
                border: Border.all(color: "#216FF6".toColor()!, width: 1),
              ),
              padding: EdgeInsets.fromLTRB(4, 2, 4, 2),
              child: Text(
                GlobalConfig.loginEntity?.organizationName ?? "--",
                style: TextStyle(color: "#216FF6".toColor(), fontSize: 12),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _getBottom() {
    return Column(
      children: [
        Container(
          height: 200,
        ),
        Container(
          width: double.infinity,
          height: 45,
          margin: EdgeInsets.fromLTRB(32, 0, 32, 0),
          child: MaterialButton(
            onPressed: () {
              DialogManager.showAlertDialog(context,
                  content: "确认要退出当前账号？", btns: ['取消', '退出'], onClick: (i) {
                if (i == 1) {
                  HDNavigator.logout();
                }
              });
            },
            child: Text(
              "退出登录",
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
            color: HDColors.green,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.zero),
          ),
        )
      ],
    );
  }

  Widget getIcon(int index) {
    if (index == 0) {
      return Icon(Icons.book_online, size: 17);
    } else if (index == 1) {
      return Icon(Icons.bookmark, size: 17);
    } else if (index == 2) {
      return Icon(Icons.update, size: 17);
    }
    return Icon(Icons.add, size: 17);
  }

  initData() {
    mineData.clear();
    mineData
      ..add(MineListData("assets/images/mine/privacy.png", "用户协议"))
      ..add(MineListData("assets/images/mine/privacy.png", "隐私协议"))
      ..add(MineListData(
          "assets/images/mine/version.png", "当前版本:${GlobalConfig.version}"));
  }
}

class MineListData {
  var img = "";
  var title = "";
  var isEnd = false;
  bool dot = false;

  MineListData(this.img, this.title);

  MineListData.end(this.img, this.title) {
    isEnd = true;
  }

  void showDot(bool showDot) {
    dot = showDot;
  }
}
